/**
 * 
 */
package foo;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import org.terukusu.ahoomsgr.YmsgPacket;
import org.terukusu.ahoomsgr.YmsgPacket.Entry;

/**
 * 友達リスト v15(0xF1[241]) のデータ部を解析するサンプル。
 * 
 * @author Teruhiko Kusunoki&lt;<a href="teru.kusu@gmail.com">teru.kusu@gmail.com</a>&gt;
 *
 */
public class ParseBuddyListSample {
	
	private String indent = "";
	
	public static void main(String[] args) throws Exception {
		new ParseBuddyListSample().exec(args);
	}
	
	public void exec(String[] args) throws Exception {
		File dataFile = new File(args[0]);
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(dataFile));
		YmsgPacket p = new YmsgPacket();
		p.parseBody(bis);
		bis.close();
		
		for (Entry entry : p.getEntries()) {
			nodeFound(entry.getKey(), entry.getValue());
		}
	}
	
	public void exec2(String[] args) throws Exception {
		File dataFile = new File(args[0]);
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(dataFile));
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		boolean isDelim = false;
		String key = null;
		byte[] data = null;
		for (int i = 0; (i = bis.read()) >= 0;) {
			if (i == 0xC0) {
				isDelim = true;
			} else if (i == 0x80) {
				if (!isDelim) {
					// おかしい
					throw new Exception("something wrong");
				} else {
					// 区切りステータスを戻す
					isDelim = false;
				}
				
				// バッファを処理
				baos.flush();
				data = baos.toByteArray();
				
				if (key == null) {
					key = new String(data);
				} else {
					nodeFound(key, data);
					key = null;
				}
				
				baos.reset();
				
			} else {
				// バッファに積む
				baos.write(i);
			}
		}
		
		// 余りがあれば処理
		baos.flush();
		if (baos.size() > 0 && key != null) {
			nodeFound(key, baos.toByteArray());
			key = null;
		}
		
		bis.close();
		baos.close();
	}
	
	public void nodeFound(String key, byte[] data) {

		if ("301".equals(key) || "303".equals(key)) {
			indent = indent.substring(0, indent.length() - 1);
		}

		System.out.println(indent + key + " = " + new String(data));

		// 300 means start list
		// 302 means start item
		if ("300".equals(key) || "302".equals(key)) {
			indent = indent + " ";
		}
	}
}
